package org.example;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

/**
 * @author zhangjg
 * @desc DruidUtil
 * @date 2021/12/31 21:54
 **/
public class DruidUtil {

    private static final Logger log = LoggerFactory.getLogger(DruidUtil.class);
    //成员变量
    private static DataSource ds;

    //静态代码块
    static {
        try {
            Properties pro = new Properties();
            Class<DruidUtil> utilClass = DruidUtil.class;
            pro.load(utilClass.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    //获取链接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //释放资源
    public static void closeSQL(Connection conn, Statement st) {
        closeSQl(conn, st, null);
    }


    public static void closeSQl(Connection conn, Statement st, ResultSet re) {
        if (re != null) {
            try {
                re.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }

        //归还conn给连接池
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }

    }

    //获取连接池
    public static DataSource getDs() {
        return ds;
    }

}
